package com.bob.usercenter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bob.usercenter.common.ErrorCode;
import com.bob.usercenter.entity.User;
import com.bob.usercenter.entity.request.QueryPage;
import com.bob.usercenter.exception.BusinessException;
import com.bob.usercenter.service.UserService;
import com.bob.usercenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import sun.security.provider.MD5;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.bob.usercenter.constant.UserConstant.USER_LOGIN_STARE;
import static com.bob.usercenter.constant.UserConstant.USER_ROLE_ADMIN;
import static java.time.LocalDateTime.now;

/**
* @author 12948
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-01-19 10:08:40
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    /**
     * 注册
     * @param userAccount
     * @param password
     * @param checkPassword
     * @return
     */
    @Override
    public int register(String userAccount,String password,String checkPassword) {
        //1.验证是否有空
        if(StrUtil.hasBlank(userAccount,password,checkPassword)){
            throw  new BusinessException(ErrorCode.PARAMS_IS_EMPTY_ERROR);
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.AUTH_ERROR);
        }
        if (password.length() < 8){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //2.判断账号是否包含特殊字符
        if (!ReUtil.isMatch("^[a-zA-Z0-9]+$", userAccount)){
            throw new BusinessException(ErrorCode.SYS_VALID_ERROR);
        }
        //3.账号不能重复
        Integer account = userMapper.selectCount(new QueryWrapper<User>().eq("userAccount", userAccount));
        if(account > 0){
            throw new BusinessException(ErrorCode.ACCOUNT_EXIST_ERROR);
        }
        //4.校验密码
        if (!password.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PWD_ERROR);
        }
        //5.对密码进行加密
        // 使用MD5算法加密密码和盐值
        String encryptedPassword = DigestUtil.md5Hex(password + "salt");
        User user = new User();
        user.setUserAccount(userAccount);
        user.setPassword(encryptedPassword);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        return userMapper.insert(user);
    }

    /**
     * d登录
     * @param userAccount
     * @param password
     * @param request
     * @return
     */
    @Override
    public User login(String userAccount, String password, HttpServletRequest request) {
        log.info("开始登录逻辑");
        //1.验证是否有空
        if(StrUtil.hasBlank(userAccount,password)){
            throw  new BusinessException(ErrorCode.PARAMS_IS_EMPTY_ERROR);
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.AUTH_ERROR);
        }
        if (password.length() < 8){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //2.判断账号是否包含特殊字符
//        if (ReUtil.isMatch("^[a-zA-Z0-9]+$", userAccount)){
//            return null;
//        }

        //3.验证密码
        // 使用MD5算法加密密码和盐值
        String encryptedPassword = DigestUtil.md5Hex(password + "salt");
        //User selectOne = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserAccount,userAccount));
        User selectOne = userMapper.selectUser(userAccount);
        System.out.println(selectOne);
        if (!selectOne.getPassword().equals(encryptedPassword)) {
            log.info("密码错误");
            throw new BusinessException(ErrorCode.PWD_ERROR);
        }

        User user = delSentitive(selectOne);

        //5.记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STARE,user);
        log.info("返回的用户信息：{}",user);

        return user;
    }


    public User delSentitive(User selectOne) {
        //4.信息脱敏
        User user = new User();
        user.setUserAccount(selectOne.getUserAccount());
        user.setId(selectOne.getId());
        user.setEmail(selectOne.getEmail());
        user.setGender(selectOne.getGender());
        user.setAvatarUrl(selectOne.getAvatarUrl());
        user.setStatus(selectOne.getStatus());
        user.setUsername(selectOne.getUsername());
        user.setPhone(selectOne.getPhone());
        user.setUserRole(selectOne.getUserRole());
        user.setCreateTime(selectOne.getCreateTime());
        return user;
    }


    /**
     * 查询用户
     * @param username
     * @return
     */
    @Override
    public List<User> queryUsers(String username,HttpServletRequest request) {
        //判断是否是管理员
        if (!isAdmin(request)) throw new BusinessException(ErrorCode.INVALID_ROLE_ERROR);
        //判断是否需要查询全部数据
        LambdaQueryWrapper<User> queryWrapper = null;
        if (StrUtil.isNotBlank(username)) {
            queryWrapper = new LambdaQueryWrapper<User>().like(User::getUsername, username);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        List<User> list = userList.stream().map(this::delSentitive).collect(Collectors.toList());
        log.info("查询到的数据：{}", userList);
        return list;
    }

    private static boolean isAdmin(HttpServletRequest request) {
        //判断是否是管理员
        User user1 = (User) request.getSession().getAttribute(USER_LOGIN_STARE);
        if(user1.getUserRole() != USER_ROLE_ADMIN){
            return false;
        }
        return true;
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    public boolean deleteUser(Long id,HttpServletRequest request) {
        //判断是否是管理员
        if (!isAdmin(request)) return false;
        return this.removeById(id);
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Override
    public int updateUser(User user) {
        return userMapper.updateById(user);
    }

    /**
     * 获取当前用户
     * @param request
     * @return 脱敏后的用户对象
     */
    @Override
    public User current(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STARE);
        Long userId = user.getId();
        User user2 = this.getById(userId);
        if(user2 == null){
            return null;
        }
        return delSentitive(user2);
    }

    /**
     * 分页查询
     * @param current
     * @param pageSize
     * @param username
     * @param request
     * @return
     */
    @Override
    public List<User> queryUsersByPage(String current,String pageSize,String username, HttpServletRequest request) {
        //判断是否是管理员
        if (!isAdmin(request)) throw new BusinessException(ErrorCode.INVALID_ROLE_ERROR);
        //判断是否需要查询全部数据
        LambdaQueryWrapper<User> queryWrapper = null;
        if (StrUtil.isNotBlank(username)) {
            queryWrapper = new LambdaQueryWrapper<User>().like(User::getUsername, username);
        }

        IPage<User> page = new Page<>( Integer.parseInt(current),Integer.parseInt(pageSize));
        //IPage<User> page = new Page<>();
        IPage<User> resultPage = userMapper.selectPage(page, queryWrapper);

        List<User> records = resultPage.getRecords();
        List<User> list = records.stream().map(this::delSentitive).collect(Collectors.toList());
        log.info("分页查询结果：{}",list.size());
        return list;
    }
}




